<template>
  <div class="import--wrap">
    <div class="table--head">
      <div :style="{ color: '#000', fontSize: '28px', fontWeight: '500' }">
        导入数据
      </div>
      <div>
        <a-radio-group v-model:value="type" @change="sexChange">
          <a-radio-button value="ALL">所有</a-radio-button>
          <a-radio-button value="男">男</a-radio-button>
          <a-radio-button value="女">女</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    <div class="table--con">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :row-key="(record) => record.sno"
        :pagination="false"
        :scroll="{ x: 1500, y: 550 }"
      >
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'sex'">
            <a-tag :color="text === '男' ? 'geekblue' : 'volcano'">{{
              text
            }}</a-tag>
          </template>
        </template>
      </a-table>
    </div>
    <div class="pagination--box">
      <a-config-provider>
        <a-pagination
          show-quick-jumper
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="handleTableChange"
        >
        </a-pagination>
      </a-config-provider>
    </div>
    <div class="table--upload">
      <div class="upload--box">
        <input
          type="file"
          ref="fileInput"
          accept=".xlsx,.xls"
          style="display: none"
          @change="handleFileChange"
        />
        <a-button
          type="dashed"
          style="width: 100%; height: 100%"
          @click="triggerFileInput"
          >选择Excel文件上传</a-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { UploadOutlined } from "@ant-design/icons-vue";
import { exportColumns } from "@/utils";
import { getChineseMedicineByPage, bulkCreate } from "@/api";
import * as XLSX from "xlsx";
import moment from "moment";
export default {
  name: "ImportData",
  data() {
    return {
      type: "ALL",
      tableData: [],
      columns: exportColumns,
      total: 0,
      current: 1,
      pageSize: 10,
      pageSizeOptions: ["10", "20", "30"],
      loading: false,
    };
  },
  components: {
    UploadOutlined,
  },
  mounted() {
    this.getChineseMedicineByPage();
  },
  methods: {
    async getChineseMedicineByPage() {
      let params = {
        page: this.current,
        limit: this.pageSize,
      };
      if (this.type != "ALL") {
        const where = {
          sex: this.type,
        };
        params.where = where;
      }
      const res = await getChineseMedicineByPage(
        window.CONFIG.server_url,
        params
      );
      if (res.code == 200) {
        this.total = res.data.count;
        this.tableData = res.data.rows;
      }
      console.log(res);
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
    },
    handleTableChange(pagination) {
      this.current = pagination;
      this.getChineseMedicineByPage();
      if (this.selectRecord) {
        this.selectedRowKeys = [];
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    sexChange() {
      this.getChineseMedicineByPage();
    },
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    async handleFileChange() {
      const file = event.target.files[0];
      if (!file) return;
      this.loading = true;
      console.log("已选择文件:", file.name);
      try {
        // 1. 读取Excel文件
        const data = await this.readExcel(file);
        // 2. 转换为tableData格式
        const tableData = this.transformToTableData(data);
        // 3. 触发父组件事件或更新数据
        if (tableData.length) {
          this.bulkCreate(tableData);
        }
      } catch (error) {
        console.error("导入失败:", error);
        this.$message.error("文件导入失败: " + error.message);
      } finally {
        this.loading = false;
        event.target.value = ""; // 重置input
      }
    },
    async bulkCreate(data) {
      const res = await bulkCreate(window.CONFIG.server_url, data);
      if (res.code == 200) {
        this.$message.success(`成功导入 ${data.length} 条数据`);
        this.getChineseMedicineByPage()
      } else {
        this.$message.error("导入失败!");
      }
    },
    readExcel(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: "array" });
            // 获取第一个工作表
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            // 转换为JSON
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            resolve(jsonData);
          } catch (error) {
            reject(error);
          }
        };
        reader.onerror = () => {
          reject(new Error("文件读取失败"));
        };
        reader.readAsArrayBuffer(file);
      });
    },
    transformToTableData(excelData) {
      console.log("excelData", excelData);
      // 表头映射关系（Excel列名 -> tableData字段名）
      const keyMapping = {
        姓名: "name",
        性别: "sex",
        年龄: "age",
        编号: "sno",
        科室: "department",
        部位: "pos",
        中医诊断: "diagnosis_chinese",
        西医诊断: "diagnosis_western",
        症状: "seen",
        医嘱: "tips",
      };
      return excelData.map((row) => {
        const tableRow = {};
        Object.keys(row).forEach((chineseKey) => {
          const trimmedKey = chineseKey.trim();
          const englishKey = keyMapping[trimmedKey];
          if (englishKey) {
            tableRow[englishKey] = row[chineseKey];
          } else {
            console.warn(`未映射的字段: ${chineseKey}`);
          }
        });
        return tableRow;
      });
    },
  },
};
</script>

<style scoped lang="less">
@import "@/assets/import.less";
</style>
